import * as echarts from '../../../components/echarts/echarts';
const app = getApp();
const requestUtil = require("../../../utils/request");
const api = require("../../../config/api");
const common = require("../../../utils/common");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    clazzName: null, // 班级名
    userInfo: {}, // 老师信息
    params: {}, // 跳转参数
    examInfo: {}, // 本次考试概况
    teacherScore: [], // 各科成绩数据
    totalStudentScoreList: [], // 总体成绩分析表格数据
    subjectArray: [], // 科目数组
    navigatorSubjectArray: [], // 切换用科目数组
    subjectIndex: 0, // 科目数组索引
    teacherScoreTableHeader: [{ // 班级概况表格表头
        prop: 'subjectName',
        width: 150,
        label: '考试科目',
      },
      {
        prop: 'examFullScore',
        width: 130,
        label: '满分'
      },
      {
        prop: 'avgScore',
        width: 130,
        label: '平均分'
      },
      {
        prop: 'lowRate',
        width: 150,
        label: '低分率'
      },
      {
        prop: 'qualifiedRate',
        width: 150,
        label: '及格率'
      },
      {
        prop: 'goodRate',
        width: 150,
        label: '优秀率'
      },
      {
        prop: 'bestRate',
        width: 150,
        label: '特优率'
      },
      {
        prop: 'gradeAvgScore',
        width: 150,
        label: '级平均分'
      },
      {
        prop: 'classStudentNum',
        width: 150,
        label: '考试人数'
      }
    ],
    totalStudentTableHeader: [{ // 总体成绩分析表格表头
        prop: 'studentName',
        width: 150,
        label: '学生姓名',
      }, {
        prop: 'chineseScore',
        width: 150,
        label: '语文成绩',
      },
      {
        prop: 'mathScore',
        width: 150,
        label: '数学成绩'
      },
      {
        prop: 'englishScore',
        width: 150,
        label: '英语成绩'
      },
      {
        prop: 'sumScore',
        width: 150,
        label: '总分'
      },
      {
        prop: 'classRank',
        width: 150,
        label: '班排名'
      },
      {
        prop: 'gradeRank',
        width: 150,
        label: '级排名'
      }
    ],
    border: true, // 表格是否开启边框
    tableNoDataMsg: '暂无数据~', // 表格无数据时显示的内容
    subjectBarIsShow: true, // 控制分数段分析是否显示
    subjectRadarIsShow: true,
    subjectBar: { // subjecCharts的渲染
      onInit: function (canvas, width, height, dpr) {
        let data = getCurrentPages()[getCurrentPages().length - 1].data;
        const barChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr
        });
        canvas.setChart(barChart);
        barChart.setOption(getBarChartOption(data));
        return barChart;
      }
    },
    radarData: {},
    subjectRadar: {
      onInit: function (canvas, width, height, dpr) {
        let data = getCurrentPages()[getCurrentPages().length - 1].data;
        const radarChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr
        });
        canvas.setChart(radarChart);
        radarChart.setOption(getRadarChartOption(data));
        return radarChart;
      }
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let params = {
      grade: options.grade,
      schoolId: common.getSchoolId(),
      clazz: options.clazz,
      examId: options.examId
    }
    this.getClassExamScore(params); // 设置班级概况表格
    this.setTotalScoreTable(params); // 设置全体学生数据表格
    this.setData({
      params: params
    })
  },
  /**
   * 获取班级考试成绩
   */
  getClassExamScore: async function (params) {
    let that = this;
    let classScoreList = await requestUtil.request('POST', api.getClassExamScore, params);
    let examInfo = classScoreList.data.data.examInfo;
    let teacherScore = classScoreList.data.data.teacherScore;

    if (teacherScore == null || !teacherScore.length > 0) {
      wx.showModal({
        title: '警告',
        content: '未找到该场考试的相关成绩，请等待教师上传成绩后再次打开。'
      })
      return;
    }
    let examFullScore = examInfo.examFullScore.split(','); // 满分
    let examSubject = examInfo.examSubject.split(','); // 科目名
    let teacherInfo = app.globalData.teacherInfo; // 能进这里就代表是老师了
    let userInfo = {};
    for (let i of teacherInfo) {
      if (params.clazz == i.clazz && params.grade == i.grade) {
        userInfo = i;
      }
    }
    let navigatorSubjectArray = [];
    // 设置跳转科目数组
    for (let e of examSubject) {
      if (userInfo.subject == e) {
        navigatorSubjectArray.push(e)
      }
    }
    navigatorSubjectArray.unshift('总分');

    // 设置表格数据中的 满分 和 各种比率
    for (let i in examSubject) {
      for (let l in teacherScore) {
        if (examSubject[i] == teacherScore[l].subjectName) {
          teacherScore[l].examFullScore = examFullScore[i];
          teacherScore[l].bestRate = (teacherScore[l].bestRate * 100).toFixed(2) + '%';
          teacherScore[l].goodRate = (teacherScore[l].goodRate * 100).toFixed(2) + '%';
          teacherScore[l].lowRate = (teacherScore[l].lowRate * 100).toFixed(2) + '%';
          teacherScore[l].qualifiedRate = (teacherScore[l].qualifiedRate * 100).toFixed(2) + '%';
        }
      }
    }
    that.setData({
      clazzName: userInfo.gradeName + userInfo.clazz + '班',
      examInfo: examInfo,
      userInfo: userInfo,
      teacherScore: teacherScore,
      subjectArray: examSubject,
      navigatorSubjectArray: navigatorSubjectArray
    })
    app.globalData.subjectArray = examSubject;
  },
  /**
   * 设置总体成绩分析表格
   */
  async setTotalScoreTable(params) {
    let that = this;
    let classStudentExamScore = await requestUtil.request('POST', api.getClassStudentExamScore, params);

    that.setData({
      totalStudentScoreList: classStudentExamScore.data.data
    });
  },

  /**
   * 切换科目
   */
  toSubjectDetail: function (e) {
    let subjectName = this.data.navigatorSubjectArray[e.detail.value]
    if (e.detail.value == 0) {
      return;
    } else {
      wx.navigateTo({
        url: '../teacher-subject-score/teacher-subject-score?grade=' + this.data.params.grade +
          "&examId=" + this.data.params.examId +
          "&clazz=" + this.data.params.clazz +
          "&schoolId=" + this.data.params.schoolId +
          "&subjectName=" + subjectName,
      })
    }
  },
  /**
   * 点击表格行时跳转进这里
   */
  onRowClick: function (e) {
    let stuId = e.detail.currentTarget.dataset.it.studentId;
    let subjectId = e.detail.currentTarget.dataset.it.subjectId;
  }
})

function getRadarChartOption(d) {
  let radarData = d.teacherScore;
  let subjectArray = d.subjectArray;
  let maxScore = d.examInfo.examFullScore.split(',')[0]; //FIXME 我这里直接取第一个值是最高分，不知道会不会有问题
  let arr = [];
  for (let i in subjectArray) {
    for (let j of radarData) {
      if (subjectArray[i] == j.subjectName) {
        let obj = {
          name: j.subjectName,
          value: [
            j.highestScore,
            j.lowestScore,
            j.avgScore
          ]
        }
        arr.push(obj);
      }
    }
  }
  return {
    backgroundColor: "#ffffff",
    legend: {
      data: subjectArray
    },
    tooltip: {
      show: true,
      alwaysShowContent: true,
      position: [10, 10],
      trigger: 'item',
      confine: true
    },
    radar: {
      // shape: 'circle',
      center: ['50%', '60%'],
      indicator: [{
          name: '最高分' + '(' + maxScore + '分)',
          max: maxScore
        },
        {
          name: '最低分' + '(' + maxScore + '分)',
          max: maxScore
        },
        {
          name: '平均分' + '(' + maxScore + '分)',
          max: maxScore
        }
      ],
      name: {
        padding: [0, -20]
      }
    },
    symbol: "circle", // 标记图形，"circle"
    series: [{
      name: '科目概况',
      type: 'radar',
      data: arr
    }]
  };
}

function getBarChartOption(d) {
  let colorObj = {
    low: '#EE6666',
    pass: '#FAC858',
    good: '#91CC75',
    best: '#5470C6'
  }
  let arr = getDaraArray(d.teacherScore);
  return {
    backgroundColor: "#ffffff",
    tooltip: {
      trigger: 'axis',
      confine: true
    },
    legend: {
      data: ['及格率', '优秀率', '特优率', '低分率']
    },
    grid: {
      left: '10%',
      right: '10%',
      bottom: '3%',
      containLabel: true
    },
    dataZoom: {
      type: "inside",
      strat: 0,
      end: 50,
      orient: "horizontal",
    },
    xAxis: {
      type: 'category',
      data: d.subjectArray,
    },
    yAxis: {
      type: 'value',
      name: "得分率",
      axisLabel: {
        formatter: '{value}%'
      }
    },
    series: [{
      data: arr.qualifiedRate,
      name: '及格率',
      type: 'bar',
      itemStyle: {
        color: colorObj.pass
      }
    }, {
      data: arr.goodRate,
      name: '优秀率',
      type: 'bar',
      itemStyle: {
        color: colorObj.good
      }
    }, {
      data: arr.bestRate,
      name: '特优率',
      type: 'bar',
      itemStyle: {
        color: colorObj.best
      }
    }, {
      data: arr.lowRate,
      name: '低分率',
      type: 'bar',
      itemStyle: {
        color: colorObj.low
      }
    }]
  };
}

/**
 * 获取横坐标数组和数据
 */
function getDaraArray(array) {
  let qualifiedRate = [];
  let goodRate = [];
  let bestRate = [];
  let lowRate = [];
  for (let i of array) {
    qualifiedRate.push(i.qualifiedRate.substr(0, i.qualifiedRate.length - 1));
    goodRate.push(i.goodRate.substr(0, i.goodRate.length - 1));
    bestRate.push(i.bestRate.substr(0, i.bestRate.length - 1));
    lowRate.push(i.lowRate.substr(0, i.lowRate.length - 1));
  }
  return {
    qualifiedRate,
    goodRate,
    bestRate,
    lowRate
  };
}